import { Button, message, notification } from 'antd';
import { useIntl } from 'umi';
import defaultSettings from '../config/defaultSettings';

const { pwa } = defaultSettings;
const isHttps = document.location.protocol === 'https:';

const clearCache = () => {
  // remove all caches
  if (window.caches) {
    caches
      .keys()
      .then((keys) => {
        keys.forEach((key) => {
          caches.delete(key);
        });
      })
      .catch((e) => console.log(e));
  }
};

// if pwa is true
if (pwa) {
  // Notify user if offline now
  window.addEventListener('sw.offline', () => {
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
  });

  // Pop up a prompt on the page asking the user if they want to use the latest version
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    const reloadSW = async () => {
      // Check if there is sw whose state is waiting in ServiceWorkerRegistration
      // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
      const worker = e.detail && e.detail.waiting;
      if (!worker) {
        return true;
      }
      // Send skip-waiting event to waiting SW with MessageChannel
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });

      clearCache();
      window.location.reload();
      return true;
    };
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.close(key);
          reloadSW();
        }}
      >
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );
    notification.open({
      message: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
      btn,
      key,
      onClose: async () => null,
    });
  });
} else if ('serviceWorker' in navigator && isHttps) {
  // unregister service worker
  const { serviceWorker } = navigator;
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then((sws) => {
      sws.forEach((sw) => {
        sw.unregister();
      });
    });
  }
  serviceWorker.getRegistration().then((sw) => {
    if (sw) sw.unregister();
  });

  clearCache();
}

// const baseUrl = 'http://192.168.43.20:8080/';
const baseUrl = 'http://10.21.3.143:8080/';

export const api = {
  getDetailedClassesIngo: baseUrl + 'classes/getDetailedClassesIngo',
  getClassesIntoUserInfo: baseUrl + 'user/getClassesIntoUserInfo',
  removeClasses: baseUrl + 'user/removeClasses',
  userLogin: baseUrl + 'user/login',
  getCurrentUser: baseUrl + 'user/getCurrentUserInfo',
  userLogout: baseUrl + 'user/logout',
  insertUserInfo: baseUrl + 'user/insertUserInfo',
  deleteUser: baseUrl + 'user/deleteUser',
  getRoleList: baseUrl + 'role/getRoleList',
  getAllDept: baseUrl + 'dept/getAllDept',
  insertOrUpdateDept: baseUrl + 'dept/insertOrUpdateDept',
  deleteDeptById: baseUrl + 'dept/deleteDeptById',
  getDeptList: baseUrl + 'dept/getDeptList',
  deleteClaasesById: baseUrl + '',
  getSimpleProfessional: baseUrl + 'professional/getSimpleProfessional',
  getAllCondition: baseUrl + 'condition/getAllCondition',
  getUserInfo: baseUrl + 'user/getUserInfo',
  updateUserInfo: baseUrl + 'user/updateUserInfo',
  getUserList: baseUrl + 'user/getUserList',
  getCourseList: baseUrl + 'course/getCourseList',
  deleteCourse: baseUrl + 'course/delete',
  getClassesList: baseUrl + 'classes/getClassesList',
  getTeacherList: baseUrl + 'user/getTeacherList',
  getEarlyYear: baseUrl + 'classes/getEarlyYear',
  updateUserClasses: baseUrl + 'user/updateUserClasses',
  getProfessionalByDeptId: baseUrl + 'professional/getProfessionalByDeptId',
  getUserInfoToSift: baseUrl + 'user/getUserInfoToSift',
  insertOrUpdateCourseInfo: baseUrl + 'course/insertOrUpdateCourseInfo',
  getCourseInfoById: baseUrl + 'course/getCourseInfoById',
  getAllRoleList: baseUrl + 'role/getAllRoleList',
  getAllPermission: baseUrl + 'permission/getAllPermission',
  deleteRole: baseUrl + 'role/deleteRole',
  getRolePermissionList: baseUrl + 'permission/getRolePermissionList',
  insertOrUpdateRole: baseUrl + 'role/insertOrUpdateRole',
  getRolePermission: baseUrl + 'role/getRolePermission',
  insertProfessional: baseUrl + 'professional/insertProfessional',
  deleteProfessional: baseUrl + 'professional/delete',
  getProfessionalList: baseUrl + 'professional/getProfessionalList',
  getFolderList: baseUrl + 'file-path/getFolderList',
  getBucketInfo: baseUrl + 'file-bucket/getBucketInfo',
  getFolderListByBucketId: baseUrl + 'file-path/getFolderListByBucketId',
  createFileFolder: baseUrl + 'file-path/createFileFolder',
  deleteFileFolder: baseUrl + '/file-path/deleteFileFolder',
  getAllFileInfo: baseUrl + 'file/getAllFileInfo',
  getSimpleUserInfo: baseUrl + 'user/getSimpleUserInfo',
  uploadFile: baseUrl + 'file/uploadFile',
  deleteFile: baseUrl + 'file/deleteFile',
  getFileSuffix: baseUrl + 'file/getFileSuffix',
  createBucket: baseUrl + '/file-bucket/createBucket',
  getStorageList: baseUrl + '/file-storage/getStorageList',
  insertOrUpdateStoreInfo: baseUrl + '/file-storage/insertOrUpdateStoreInfo',
  getStoreInfoById: baseUrl + 'file-storage/getStoreInfoById',
  deleteStoreInfoById: baseUrl + 'file-storage/deleteStoreInfoById',
  getStoreFileInfo: baseUrl + 'file/getStoreFileInfo',
  getStoreFileById: baseUrl + 'file/getStoreFileById',
  updateStoreFileInfo: baseUrl + 'file/updateStoreFileInfo',
  insertStorageFileInfo: baseUrl + 'file/insertStorageFileInfo',
  deleteStoreFileById: baseUrl + 'file/deleteStoreFileById',
  getStorageListByIds: baseUrl + 'file-storage/getStorageListByIds',
  addFileDownload: baseUrl + 'file/addFileDownload',
  getFileMessage: baseUrl + 'file-message/getFileMessage',
  getComplexFileInfo: baseUrl + 'file/getComplexFileInfo',
  getFileAllSuffix: baseUrl + 'file/getFileAllSuffix',
  getPrivateFileList: baseUrl + 'file/getPrivateFileList',
  uploadPrivateFile: baseUrl + 'file/uploadPrivateFile',
  upLoadApproveFile: baseUrl + 'file-approve/upLoadApproveFile',
  getPrivateApproveFileList: baseUrl + 'file-approve/getPrivateApproveFileList',
  cancelFileApprove: baseUrl + 'file-approve/cancelFileApprove',
  getPrivateFileInfoMsg: baseUrl + 'file-message/getPrivateFileInfoMsg',
  getDeptApproveFile: baseUrl + 'dept/getDeptApproveFile',
  getDeptApproverList: baseUrl + 'file-approve/getDeptApproverList',
  passApprovalFile: baseUrl + 'file-approve/passApprovalFile',
  failApprovalFile: baseUrl + 'file-approve/failApprovalFile',
  reUpLoadApproveFile: baseUrl + 'file-approve/reUpLoadApproveFile',
  updatePrivateUserInfo: baseUrl + 'user/updatePrivateUserInfo',
  canUpdateUserPassWord: baseUrl + 'user/canUpdateUserPassWord',
  modifyPassword: baseUrl + 'user/modifyPassword',
  modifyPrivatePassword: baseUrl + 'user/modifyPrivatePassword',
};
